// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class RPG extends cc.Component {

    @property(cc.Node)
    img1: cc.Node = null;

    @property(cc.Node)
    node1: cc.Node = null;

    speed = 300

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.img1.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)

    }

    onTouchStart(evt: cc.Event.EventTouch) {
        let flag = this.checkPolygonCollider(this.img1, evt.getLocation())
        if (flag) {
            console.log('qqqqqqqqqqqqqqqqq')
        }
    }

    update(dt) {
        this.node1.angle -= dt * this.speed;
    }

    /**
     * 检查按钮点击是否在多边形内
     * @param node 按钮
     * @param e   点击事件
     */
    private checkPolygonCollider(node: cc.Node, pos: cc.Vec2) {
        let collider = node.getComponent(cc.PolygonCollider);
        let points = collider.points;
        let local = node.convertToNodeSpaceAR(pos);
        let bHit = cc.Intersection.pointInPolygon(local, points);
        return bHit;
    }


    /**
     * 加载预制体
     * @param {string} path
     * @param {*} compFunc
     * @param {*} thisObj
     * @memberof LoadAsync
     */
    public loadPrefab(path: string, region: string = "main", bundle?: cc.AssetManager.Bundle): Promise<cc.Prefab> {
        return new Promise((resolve, reject) => {
            if (!path) {
                console.error("AssertMgr -> preloadPrefab error. path is null");
                reject(null);
                return;
            };
            bundle = bundle || cc.resources;
            let res: cc.Prefab = bundle.get(path);
            if (res) {
                resolve(res);
            } else {
                bundle.load(
                    path,
                    cc.Prefab,
                    (finish: number, total: number) => {

                    },
                    (err: Error | null, asset: cc.Prefab) => {
                        if (err != undefined) {
                            console.error("AssertMgr -> preloadPrefab error. path : ", path);
                            reject(err);
                            return;
                        };
                        resolve(asset);
                    }
                );
            };
        });
    };
}
